package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);

        // 计算营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 查询date日期对应的营业额数据，营业额：状态为“已完成”的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            log.info("营业额：{}", turnover);
            turnover = turnover == null ? 0.0 : turnover;  // 如果当天没有营业额，转为0.0

            turnoverList.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 存放begin和end之间每天的日期
        List<LocalDate> dateList = getDateList(begin, end);
        // 存放新增用户数量
        List<Integer> newUserList = new ArrayList<>();
        //存放总用户数量
        List<Integer> totalUserList = new ArrayList<>();


        // 计算新增用户量
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer newUserCount = userMapper.countByMap(new HashMap() {{
                put("end", endTime);
                put("begin", beginTime);
            }});
            newUserCount = newUserCount == null ? 0 : newUserCount;
            log.info("新增用户：{}", newUserCount);
            newUserList.add(newUserCount);

            // 计算总用户量
            Integer totalUserCount = userMapper.countByMap(new HashMap() {{
                put("end", endTime);
            }}) + newUserCount;
            log.info("总用户：{}", totalUserCount);
            totalUserList.add(totalUserCount);

        }


        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        // 存放日期列表
        List<LocalDate> dateList = getDateList(begin, end);


        List<Integer> orderCountList = new ArrayList<>();  // 每日订单数
        List<Integer> validOrderCountList = new ArrayList<>();  // 每日有效订单数
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 计算每日订单数
            Map map = new HashMap() {{
                put("begin", beginTime);
                put("end", endTime);
            }};
            Integer orderCount = orderMapper.getOrderCountByMap(map);
            orderCount = orderCount == null ? 0 : orderCount;
            orderCountList.add(orderCount);

            // 计算每日有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.getOrderCountByMap(map);
            validOrderCount = validOrderCount == null ? 0 : validOrderCount;
            validOrderCountList.add(validOrderCount);
        }

        // 计算订单总数
        Integer totalOrderCount = orderCountList.stream()
                .reduce(0, Integer::sum);
        log.info("订单总数：{}", totalOrderCount);

        // 计算有效订单总数
        Integer validOrderCount = validOrderCountList.stream()
                .reduce(0, Integer::sum);
        log.info("有效订单总数：{}", validOrderCount);

        // 计算订单完成率：有效订单总数 / 订单总数 * 100%
        Double orderCompletionRate = totalOrderCount == 0 ? 0.0 :
                validOrderCount.doubleValue() / totalOrderCount.doubleValue();
        log.info("订单完成率：{}", orderCompletionRate);

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量前十
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTopTen(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTopTenList = orderMapper.getSalesTopTen(beginTime, endTime);
        log.info("销售排名前十：{}", salesTopTenList);

        List<String> nameList = salesTopTenList.stream()
                .map(GoodsSalesDTO::getName)
                .toList();

        List<String> numberList = salesTopTenList.stream()
                .map(GoodsSalesDTO -> String.valueOf(GoodsSalesDTO.getNumber()))
                .toList();

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出营业数据报表
     *
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 1、查询数据库
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        // 查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        // 2、通过POI将数据写入excel文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            // 基于模板文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            // 获取表格文件：sheet1
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            // 填充概览数据
            sheet1.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);  // 时间
            sheet1.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());  // 营业额
            sheet1.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());  // 订单完成率
            sheet1.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());  // 新增用户数
            sheet1.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());  // 有效订单数
            sheet1.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());  // 平均客单价

            // 填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                int currentLocation = 7 + i;
                sheet1.getRow(currentLocation).getCell(1).setCellValue(date.toString());
                sheet1.getRow(currentLocation).getCell(2).setCellValue(businessData.getTurnover());
                sheet1.getRow(currentLocation).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet1.getRow(currentLocation).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet1.getRow(currentLocation).getCell(5).setCellValue(businessData.getUnitPrice());
                sheet1.getRow(currentLocation).getCell(6).setCellValue(businessData.getNewUsers());
            }

            // 3、通过输出流，将excel文件，下载至客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            outputStream.close();
            excel.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }


    }

    /**
     * 存放日期列表
     *
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}
